const express = require('express');
const StatsTracker = require('./stats-tracker');

// Create stats tracker instance
const statsTracker = new StatsTracker();

// Create router for stats API endpoints
const statsRouter = express.Router();

// Get summary statistics
statsRouter.get('/summary', (req, res) => {
    try {
        const summary = statsTracker.getSummaryStats();
        const users = statsTracker.getStats();
        const historical = statsTracker.getHistoricalData(12); // Last hour (12 * 5min intervals)
        
        res.json({
            summary,
            users,
            historical,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        console.error('Error fetching summary stats:', error);
        res.status(500).json({ error: 'Failed to fetch statistics' });
    }
});

// Get user-specific statistics
statsRouter.get('/user/:username', (req, res) => {
    try {
        const { username } = req.params;
        const userStats = statsTracker.getStats(username);
        
        if (!userStats) {
            return res.status(404).json({ error: 'User not found' });
        }
        
        res.json({
            username,
            stats: userStats,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        console.error('Error fetching user stats:', error);
        res.status(500).json({ error: 'Failed to fetch user statistics' });
    }
});

// Get top users by metric
statsRouter.get('/top/:metric', (req, res) => {
    try {
        const { metric } = req.params;
        const { limit = 10, interval } = req.query;
        
        const validMetrics = ['requests', 'duration', 'size', 'errors'];
        if (!validMetrics.includes(metric)) {
            return res.status(400).json({ 
                error: `Invalid metric. Must be one of: ${validMetrics.join(', ')}` 
            });
        }
        
        const topUsers = statsTracker.getTopUsers(metric, parseInt(limit), interval);
        
        res.json({
            metric,
            limit: parseInt(limit),
            interval: interval || 'current',
            users: topUsers,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        console.error('Error fetching top users:', error);
        res.status(500).json({ error: 'Failed to fetch top users' });
    }
});

// Get interval statistics
statsRouter.get('/intervals', (req, res) => {
    try {
        const { count = 12 } = req.query;
        const historical = statsTracker.getHistoricalData(parseInt(count));
        
        res.json({
            intervalCount: parseInt(count),
            data: historical,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        console.error('Error fetching interval stats:', error);
        res.status(500).json({ error: 'Failed to fetch interval statistics' });
    }
});

// Get current interval statistics
statsRouter.get('/current', (req, res) => {
    try {
        const currentInterval = statsTracker.getCurrentInterval();
        const intervalStats = statsTracker.getIntervalStats(currentInterval);
        
        res.json({
            interval: currentInterval,
            stats: intervalStats,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        console.error('Error fetching current interval stats:', error);
        res.status(500).json({ error: 'Failed to fetch current interval statistics' });
    }
});

// Export router and tracker
module.exports = {
    statsRouter,
    statsTracker
};